package com.grape.service.system.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.grape.dao.system.MenuRepository;
import com.grape.dao.system.PermissionRepository;
import com.grape.dao.system.RoleRepository;
import com.grape.domain.system.Menu;
import com.grape.domain.system.Permission;
import com.grape.domain.system.Role;
import com.grape.service.system.MenuService;
import com.grape.service.system.PermissionService;
import com.grape.service.system.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

	@Autowired
	private MenuRepository mr;
	
	@Autowired
	private PermissionRepository pr;
	
	@Autowired
	private RoleRepository rr;
	
	@Override
	public List<Role> findAll() {
		return rr.findAll();
	}

	@Override
	public void save(Role model, Integer[] permissionIds, String menuIds) {
		
		rr.save(model);
		
		// 查询菜单给角色
		if (menuIds!=null) {
			String[] split = menuIds.split(",");
			for (String string : split) {
				Integer menuId = Integer.parseInt(string);
				Menu menu = mr.findOne(menuId);
				if (menu != null) {
					model.getMenus().add(menu);
				} 
			}
		}
		
		
		// 查询权限给角色
		if (permissionIds!=null) {
			for (Integer integer : permissionIds) {
				Permission permission = pr.findOne(integer);
				if (permission!=null) {
					model.getPermissions().add(permission);
				}
			}
			
		}
		
		
	}

	@Override
	public void delete(String ids) {
		String[] split = ids.split(",");
		for (String id : split) {
			Integer parseInt = Integer.parseInt(id);
			rr.delete(parseInt);
		}
	}


}
